﻿using System;
using DapperLambdaSQL.Model.Exceptions;

namespace DapperLambdaSQL.Model
{
    internal class SqlString
    {
        /// <summary>
        /// 主语
        /// </summary>
        public string Subject { get; private set; }

        /// <summary>
        /// 设置 主语
        /// </summary>
        /// <param name="sql"></param>
        public void SetSubject(string sql)
        {
            if (string.IsNullOrEmpty(sql))
            {
                throw new ArgumentNullException("SQL主语");
            }
            if (!sql.StartsWith("SELECT")
               && !sql.StartsWith("INSERT")
               && !sql.StartsWith("UPDATE")
               && !sql.StartsWith("DELETE"))
            {
                throw new ArgumentException("SQL语句设置错误", "SQL主语");
            }
            Subject = sql;
        }

        /// <summary>
        /// WHERE 字句
        /// </summary>
        public string Where { get; set; }

        /// <summary>
        /// ORDER BY 字句
        /// </summary>
        public string OrderBy { get; set; }

        /// <summary>
        /// 分页字句
        /// </summary>
        public string Paging { get; set; }

        private int skipCount;

        /// <summary>
        /// 跳过的数量 默认0行
        /// </summary>
        public int SkipCount
        {
            get
            {
                if (skipCount < 0)
                {
                    skipCount = 0;
                }
                return skipCount;
            }
            set
            {
                skipCount = value;
            }
        }

        private int takeCount;

        /// <summary>
        /// 查询的数量 默认100行
        /// </summary>
        public int TakeCount
        {
            get
            {
                if (takeCount <= 0)
                {
                    takeCount = 100;
                }
                return takeCount;
            }
            set
            {
                takeCount = value;
            }
        }

        /// <summary>
        /// 完整的 SELECT 语句
        /// </summary>
        /// <returns></returns>
        public string QuerySql => Subject + Where + OrderBy + Paging;

        /// <summary>
        /// 完整的 UPDATE / DELETE 语句
        /// </summary>
        /// <returns></returns>
        public string ModifySql()
        {
            if (string.IsNullOrEmpty(Where))
            {
                throw new BuildSQLException("更新或删除操作必须带条件！");
            }
            return Subject + Where;
        }
    }
}